package com.asiainfo.controller;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuples;

import java.lang.annotation.Retention;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
@RestController
@RequestMapping("sse")
public class SseController {
    @GetMapping("/randomNumbers")
    public Flux<ServerSentEvent<Integer>> randomNumbers() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
                .map(data -> ServerSentEvent.<Integer>builder()
                        .event("random")
                        .id(Long.toString(data.getT1()))
                        .data(data.getT2())
                        .build());
    }

    @GetMapping("/randomString")
    public Flux<ServerSentEvent<String>> randomString() {
        return Flux.interval(Duration.ofSeconds(2))
                .map(data -> ServerSentEvent.<String>builder()
                        .event("random")
                        .id(String.valueOf(Math.random()))
                        .data("dd")
                        .build());
    }

    @CrossOrigin
    @GetMapping("/testMobile")
    public Flux<ServerSentEvent<String>> randomString1() {
        return Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
            }
            return "flux data--" + i;
        }))
                .map(data -> ServerSentEvent.<String>builder()
                        .event("random")
                        .id(String.valueOf(Math.random()))
                        .data(data)
                        .build());
    }

}
